
import json
import re
from datetime import datetime
from db_function import DataBaseFunction

from log_analysis import LogAnalysis

class BleFunction:

    def set_host(self, order_dict):
        '''order_dict:
        {
            "task_type": "set_host",
            "task_id": "2",	# 任务ID号
            "data": {
                "host": "192.168.33.33",
                "netmask": "255.255.255.0"
            }
        }
        '''

        if not order_dict["task_type"] == "set_host":

            return {
                "type": "callback", 
                "data": {
                    "task_type": "set_host", 
                    "task_id": order_dict["task_id"], 
                    "result": "命令格式错误"
                
                }
            }
        
        with open("ble_set_host.conf", 'w') as f:

            f.write(json.dumps(order_dict))

        return {
            "type": "callback", 
            "data": {
                "task_type": "set_host", 
                "task_id": order_dict["task_id"], 
                "result": "success"
            
            }
        }

    def get_base_info_(self):
        '''order_dict:
        {
            "task_type": "get_base_info",
            "task_id": "2",	# 任务ID号
            "data": ""
        }'''

        with DataBaseFunction() as df:

            base_staion_info = df.get_base_staion_info()

            brackets_info = df.get_brackets_info()

            sensors_info = df.get_sensors_info() # TODO 对应的最后一次要解析出来

        return {
            "type": "callback", 
            "data": {
                "task_type": "get_sensor_info", 
                "task_id": "2", 
                "result":{
                    "base_staion_info": base_staion_info,
                    "brackets_info": brackets_info,
                    "sensors_info": sensors_info

                }
            }

        }
    
    def get_base_info(self, order_dict):
        '''order_dict:
        {
            "task_type": "get_base_info",
            "task_id": "2",	# 任务ID号
            "data": ""
        }'''

        with DataBaseFunction() as df:

            base_staion_info = df.get_base_staion_info()

        return {
            "type": "callback", 
            "data": {
                "task_type": "get_base_info", 
                "task_id": order_dict["task_id"], 
                "result":{
                    "base_staion_info": base_staion_info,
                }
            }

        }
    
    def get_sensor_info_by_log(self):

        regex = r"{'codr': '4/5', 'data': '.*?', 'datetime': '(.*?)', 'datr': '.*?', 'devaddr': '(.*?)', .*?, 'text': '(.*?)'}"

        with open("/var/log/receive_ns_task.log") as f:
            log_content = f.read()
            result = re.findall(regex, log_content)
            

        return result
    
    def get_sensor_info_last(self, sensor_mac):

        '''return ('2023-10-28T01:19:55Z', '9A8BE4C6', '058A0B000E00040011EF73')'''

        sensor_info = self.get_sensor_info_by_log()

        for i in range(len(sensor_info)-1, -1, -1):
            
            if sensor_info[i][1] == sensor_mac:


                return sensor_info[i]
            
        else:

            return None

    
    def get_sensor_info(self, order_dict):

        '''{
            "task_type": "get_sensor_info",
            "task_id": "2",	# 任务ID号
            "data": {"base_station_id": 1}
        }'''

        la = LogAnalysis()

        base_station_id = order_dict["data"]["base_station_id"]

        with DataBaseFunction() as df:

            base_station_info = df.get_base_station_info_by_id(base_station_id)

            brackets_info = df.get_brackets_info_by_base_station_id(base_station_id)

            sensors_info = []

            for brackets in brackets_info:

                info = df.get_sensors_info_by_brackets_id(brackets["id"])

                for ii in info:

                    last_info = la.get_sensor_info_last(ii["mac"])

                    if last_info:

                        ii["value"] = last_info[2]

                        datetime_obj = datetime.strptime(last_info[0], "%Y-%m-%dT%H:%M:%SZ")

                        ii["value_last_time"] = int(datetime.timestamp(datetime_obj))

                    else:

                        ii["value"] = None
                        ii["value_last_time"] = None

                sensors_info.extend(info)

        result =  {
            "base_staion_info": base_station_info,
            "brackets_info": brackets_info,
            "sensors_info": sensors_info
        }

        return {
                "type": "callback", 
                "data": {
                    "task_type": "get_sensor_info", 
                    "task_id": order_dict["task_id"], 
                    "result": result
                }
        }
    
    def order_insert(self, order_dict):
        '''
        {
            "task_type": "set_acquisition_cycle",													
            "task_id": "183",																		# 任务ID号
            "data": {
                "devaddr_list": ["943EBDE7", "92B18DD5"],
                "value": "00"  # 00:不采集; 01:连续采集; 02:1秒一次; 03:5秒一次; 04:10秒一次； 05：30秒一次； 
            }
        }
        '''

        with DataBaseFunction() as df:

            try:

                df.insert_task(task_info=order_dict)

            except Exception as e:

                return {
                    "type": "callback", 
                    "data": {
                        "task_type": order_dict["task_type"], 
                        "task_id": order_dict["task_id"], 
                        "task_status": "fail", 
                        "notes": str(e), 
                        "result": None
                    }
                }


        return {
                "type": "callback", 
                "data": {
                    "task_type": order_dict["task_type"], 
                    "task_id": order_dict["task_id"], 
                    "task_status": "receive", 
                    "notes": None, 
                    "result": None
                }
        }
    
    def get_task_status(self, order_dict):
         
        '''{
                "task_type": "get_task_status",
                "task_id": "2",	# 任务ID号
            }
        '''

        with DataBaseFunction() as df:

            info = df.selete_tasks_by_id(order_dict["task_id"])

        return {
            "type": "callback",

            "data":{
                "task_type": info["task_type"],
                "task_id": info["task_id"], 
                "task_status": info["status"], 
                "notes": None, 
                "result": info["return_data"], 
            }
        }
         


if __name__ == "__main__":

    from setting import logger

    b = BleFunction()

    task = {
            "task_type": "get_sensor_info",
            "task_id": "2",	# 任务ID号
            "data": {"base_station_id": 1}
        }

    x = b.get_sensor_info(task) 

    logger.info(x)



